﻿using CommonEngine;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Net;

namespace WebAdmin.Filter
{
    /// <summary>
    /// 全局日志过滤
    /// </summary>
    public class ErrorHandlingFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<ErrorHandlingFilter> _logger;
        /// <summary>
        /// 构造
        /// </summary>
        public ErrorHandlingFilter(ILogger<ErrorHandlingFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 发生异常时，过滤执行 
        /// </summary>
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);

            if (context.Exception is AdminCommonException)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Result = new ObjectResult(new ReturnData { Status = false, Message = context.Exception.Message });
            }
            else if (context.Exception is AdminErrorException)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                context.Result = new ObjectResult(new ReturnData { Status = false, Message = context.Exception.Message });
                //写入文件日志
                _logger.LogError(new EventId(context.Exception.HResult), context.Exception, $"{context.HttpContext.Request.Path}  {context.HttpContext.Request.Method}  {context.Exception}");
            }
            else
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = new ObjectResult(new ReturnData { Status = false, Message = context.Exception.Message });
                //写入文件日志
                _logger.LogError(new EventId(context.Exception.HResult), context.Exception, $"{context.HttpContext.Request.Path}  {context.HttpContext.Request.Method}  {context.Exception}");
            }
        }
    }
}
